<template>
    <div class="course-center-container">
        <Header />

        <div class="main-content">
            <!-- 搜索栏 -->
            <section class="search-bar">
                <el-input v-model="searchName" placeholder="请输入课程名称" clearable @clear="onSearch" @keyup.enter="onSearch"
                    style="width: 300px;">
                    <template #append>
                        <el-button icon="Search" @click="onSearch" />
                    </template>
                </el-input>
            </section>

            <!-- 加载中提示 -->
            <section v-if="loading" class="loading">
                <el-skeleton :rows="4" animated />
            </section>

            <!-- 课程网格 -->
            <section v-else class="course-grid">
                <el-card v-for="course in courses" :key="course.id" class="course-card" shadow="hover">
                    <router-link :to="course.courseUrl || '/'">
                        <img :src="course.coverUrl" alt="course.name" class="course-cover" />
                        <div class="course-info">
                            <p class="course-name">{{ course.name }}</p>
                            <p class="course-count">播放量: {{ course.count }}</p>
                        </div>
                    </router-link>
                </el-card>
            </section>

            <!-- 分页组件 -->
            <div class="pagination">
                <el-pagination :key="'pagination-' + paginationKey.value" layout="prev, pager, next" :total="total"
                    :hide-on-single-page="true" :page-size="pageSize" v-model.current-page="pageNum"
                    @current-change="handlePageChange" />
            </div>
        </div>
        <!-- <div style="margin: 20px; font-size: 16px;">
            当前页码：{{ pageNum }} / 总页数：{{ Math.ceil(total / pageSize) }}
        </div> -->
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import { getCourse, getPage } from '@/api/course'
import { loadImage } from '@/api/file'

// 分页参数
const pageNum = ref(1)
const pageSize = ref(15)
const total = ref(0) // 总页数
const searchName = ref('')
const loading = ref(false)
const paginationKey = ref(0)
// 课程数据
const courses = ref([])

// 获取课程列表
const fetchCourses = async () => {
    loading.value = true
    try {
        let offset = (pageNum.value - 1) * pageSize.value
        console.debug(offset, pageSize.value, searchName.value);
        const res = await getCourse(offset, pageSize.value, searchName.value)

        if (res.code === 100 && Array.isArray(res.data)) {
            // 加载图片路径
            const processed = await Promise.all(
                res.data.map(async (course) => {
                    const coverUrl = await loadImage(course.coverUrl, '/default-course.jpg')
                    return { ...course, coverUrl }
                })
            )

            courses.value = processed
        } else {
            console.warn('获取课程失败或格式错误', res)
        }
    } catch (error) {
        console.error('请求课程失败:', error)
    } finally {
        loading.value = false
    }
}

// 获取总页数并更新 total
const fetchTotal = async () => {
    try {
        const res = await getPage(pageSize.value)

        if (res.code === 100 && typeof res.data === 'number') {
            total.value = res.data
        } else {
            console.warn('获取总页数失败或格式错误', res)
        }
    } catch (error) {
        console.error('请求总页数失败:', error)
    }
}

// 统一加载数据方法
const fetchData = async () => {
    loading.value = true
    await Promise.all([fetchCourses(), fetchTotal()])
    loading.value = false
}

// 搜索事件
const onSearch = () => {
    pageNum.value = 1
    fetchData()
}

// 分页切换
const handlePageChange = async (newPage) => {
    pageNum.value = Math.min(Math.max(1, newPage), Math.ceil(total.value / pageSize.value)) // 确保页码合法
    loading.value = true
    await fetchCourses()
    loading.value = false

    // 延迟一小段时间再触发 key 变化，确保组件重新渲染
    setTimeout(() => {
        paginationKey.value += 1
    }, 50)

    window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 页面加载时初始化
onMounted(() => {
    fetchData()
})
</script>

<style lang="scss" scoped>
.course-center-container {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}

.main-content {
    flex: 1;
    width: 100%;
    max-width: 80vw;
    margin: 40px auto;
    padding: 20px;
    box-sizing: border-box;
    border-radius: 10px;
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(2px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
    color: white;
}

.search-bar {
    margin-bottom: 30px;
    display: flex;
    justify-content: center;
}

.loading {
    margin-top: 40px;
}

.course-grid {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 20px;
}

.course-card {
    border-radius: 8px;
    overflow: hidden;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    cursor: pointer;
}

.course-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
}

.course-cover {
    width: 100%;
    height: 140px;
    object-fit: cover;
    border-radius: 4px;
}

.course-info {
    padding: 10px;

    .course-name {
        font-size: 16px;
        font-weight: bold;
        margin: 0 0 5px;
        color: #333;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .course-count {
        font-size: 14px;
        color: #888;
        margin: 0;
    }
}

.pagination {
    margin-top: 40px;
    display: flex;
    justify-content: center;
}

@media (max-width: 991px) {
    .course-grid {
        grid-template-columns: repeat(3, 1fr);
    }
}

@media (max-width: 767px) {
    .course-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}
</style>